<?php
/**
 * 模型发送
 * @return
 * @author yuncran@126.com
 */

namespace app\services;

use app\model\BuyGiftLogModel;
use app\model\FriendModel;
use app\model\GoldUserLogModel;
use app\model\MessageModel;
use app\model\MessageTemplateModel;
use app\model\SystemMessageModel;
use app\model\TrendsCommentModel;
use app\model\TrendsMagModel;
use app\model\TrendsModel;
use app\model\UserModel;
use GatewayClient\Gateway;
use think\facade\Cache;
use think\facade\Db;

class SendMessageServices
{

    /**检查发送是否在线权限
     * @param $user_id 当前登录会员
     * @param $friend_id 要通知会员
     * @param $type 通知类型
     * @param $use_id 公用ID
     * @return true|null normal在线状态
     * @author yuncran@126.com
     */
    public static function checkUserSendMessage($user_id, $friend_id, $type, $use_id = 0)
    {
        /**@var 在线直接推送记录   不在线如数据库 登录展示信息 */
        Db::startTrans();
        try {
            $result = self::sendMessage($user_id, $friend_id, $type, $use_id);
            Db::commit();
        } catch (\Throwable $throwable) {
            Db::rollback();
            return echoShutDown(lang('操作失败'), 400);
        }
        return $result;
    }


    /**
     * @param $user_id
     * @param $friend_id
     * @param $type // trends = 动态消息提醒、
     * @param $use_id //通用ID
     * @return null
     * @author yuncran@126.com
     */
    public static function sendMessage($user_id, $friend_id, $type, $use_id)
    {

        switch ($type) {
            case 'trends':
                $to_user = UserModel::getUserInfoFind(['id' => $friend_id], 'id,nickname,is_speak_me,is_comment_me,is_private,is_mail');
                if ($to_user['is_speak_me'] == 1 || $to_user['is_speak_me'] == 0) {
                    $trends = TrendsModel::where('id', $use_id)->field('id,title')->find();
                    $user_message_data = ['username' => $to_user['nickname'], 'trends_name' => $trends['title']];
                    $getValue = MessageService::getValue('100003', $user_message_data);

                    $message = array(
                        'user_id' => $user_id,
                        'describe' => env('APP_DEBUG') ? '会员为【 ' . $user_id . ' 】发布的动态' : '',
                        'content' => MessageService::getTemplate('100003', $user_message_data),

                        'content_tw' => $getValue['result_message_tw'],
                        'content_us' => $getValue['result_message_us'],
                        'content_jp' => $getValue['result_message_jp'],
                        'content_kr' => $getValue['result_message_kr'],
                    );
                    self::websocketSendMsg($friend_id, $type, $message);
                    self::websocketSendMsg($friend_id, 'system_message', $message);
                    //增加系统消息
                    SystemMessageModel::create($message);
                }
                break;
            case 'trends_mag':
                $to_user = UserModel::getUserInfoFind(['id' => $friend_id], 'id,nickname,is_speak_me,is_comment_me,is_private,is_mail');
                $user_message_data = ['username' => $to_user['nickname'], 'trends_name' => '', 'money' => 10];
                $shape = array(
                    'user_id' => $user_id, 'trends_ids' => $use_id, 'users' => $friend_id,
                    'is_read' => 0,
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'type' => 2,
                );
                TrendsMagModel::create($shape);
                $message = array(
                    'user_id' => $user_id,
                    'describe' => env('APP_DEBUG') ? '会员为【 ' . $user_id . ' 】发布的动态' : '',
                    'content' => MessageService::getTemplate('100003', $user_message_data),
                );
                self::websocketSendMsg($friend_id, 'trends_mag', $message);
                break;
            //动态评论
            case 'trends_comment':
                $user = UserModel::getUserInfoFind(['id' => $user_id], 'id,nickname,is_speak_me,is_comment_me,is_private,is_mail');
                $TrendsComment = TrendsCommentModel::where('id', $use_id)->field('id,content,trends_id')->find();
                $trends = TrendsModel::where('id', $TrendsComment->trends_id)->value('content');
                $user_message_data = ['username' => $user['nickname'], 'trends_name' => substr($trends, 0, 3)];
                $getValue = MessageService::getValue('100003', $user_message_data);
                $message = array(
                    'user_id' => $friend_id,
                    'describe' => env('APP_DEBUG') ? '会员为【 ' . $user_id . ' 】发布的动态' : '',
                    'content' => MessageService::getTemplate('100003', $user_message_data) . $TrendsComment['content'],
                    'content_tw' => $getValue['result_message_tw'] . $TrendsComment['content'],
                    'content_us' => $getValue['result_message_us'] . $TrendsComment['content'],
                    'content_jp' => $getValue['result_message_jp'] . $TrendsComment['content'],
                    'content_kr' => $getValue['result_message_kr'] . $TrendsComment['content'],
                );

                $to_user = UserModel::getUserInfoFind(['id' => $friend_id], 'id,nickname,is_speak_me,is_comment_me,is_private,is_mail');
                if ($to_user['is_comment_me'] == 1 || $to_user['is_comment_me'] == 0) {
                    self::websocketSendMsg($friend_id, $type, $message);
                    //增加系统消息
                    SystemMessageModel::create($message);
                }
                break;

            case 'simple':

            case 'system_message': //系统消息
                self::websocketSendMsg($friend_id, $type, '更新系统消息');
                $to_user = UserModel::getUserInfoFind(['id' => $user_id], 'id,nickname,is_speak_me,is_comment_me,is_private,is_mail');
                $res = BuyGiftLogModel::alias('log')->leftJoin('fa_gift gift', 'gift.id=log.gift_id')
                    ->where('log.id', $use_id)->field(['log.*', 'gift.title'])->find();
                $user_message_data = ['username' => $res['type'] == 1 ? lang('匿名') : $to_user['nickname'], 'gift_name' => $res['title'], 'money' => $res['money']];

                $getValue = MessageService::getValue('100002', $user_message_data);
                $message = array(
                    'user_id' => $friend_id,
                    'money' => $res['money'],
                    'describe' => env('APP_DEBUG') ? '会员为【 ' . $user_id . ' 】 送礼物' : '',
                    'content' => MessageService::getTemplate('100002', $user_message_data) . $res['remarks'],
                    'content_tw' => $getValue['result_message_tw'] . $res['remarks'],
                    'content_us' => $getValue['result_message_us'] . $res['remarks'],
                    'content_jp' => $getValue['result_message_jp'] . $res['remarks'],
                    'content_kr' => $getValue['result_message_kr'] . $res['remarks'],
                );
                //增加系统消息
                SystemMessageModel::create($message);
                if (!empty($res)) {
                    //增加聊天 chat gift
                    $messageTemplate = MessageTemplateModel::where(['code' => '100002'])->find();
                    $replacements = array('{name}' => $user_message_data['username'], '{gift_name}' => $user_message_data['gift_name'], '{money}' => $user_message_data['money']);
                    $result_message = str_replace(array_keys($replacements), array_values($replacements), $messageTemplate['describe']);
                    $shape = array(
                        'from_user' => $user_id, 'to_user' => $friend_id, 'sendid' => $user_id,
                        'content' => $result_message . $res['remarks'],
                        'type' => 'gift',
                        'is_read' => 0,
                        'create_time' => date('Y-m-d H:i:s', time()),
                    );
                    self::websocketSendMsg($friend_id, 'chat', $shape);
                    $shape_create = array(
                        'from_user' => $user_id, 'to_user' => $friend_id,
                        'content' => $result_message . $res['remarks'],
                        'type' => 'gift',
                        'is_read' => 0,
                        'friend_id' => self::getFriendId($user_id, $friend_id),
                        'create_time' =>  time(),
                    );
                    event('Service', ['friend_id' => $shape_create['friend_id'],]);
                    MessageModel::create($shape_create);
                }
                break;
            case 'system_smg': //系统消息
                self::websocketSendMsg($friend_id, 'system_message', '更新系统消息');
                $to_user = UserModel::getUserInfoFind(['id' => $user_id], 'id,nickname,is_speak_me,is_comment_me,is_private,is_mail');
                $res = GoldUserLogModel::where('id', $use_id)->find();
                $user_message_data = ['username' => $to_user['nickname'], 'money' => $res['money']];
                $getValue = MessageService::getValue('100005', $user_message_data);
                $message = array(
                    'user_id' => $friend_id,
                    'money' => $res['money'],
                    'describe' => env('APP_DEBUG') ? '会员为【 ' . $user_id . ' 】 送金币' : '',
                    'content' => MessageService::getTemplate('100005', $user_message_data),
                    'content_tw' => $getValue['result_message_tw'] . $res['remarks'],
                    'content_us' => $getValue['result_message_us'] . $res['remarks'],
                    'content_jp' => $getValue['result_message_jp'] . $res['remarks'],
                    'content_kr' => $getValue['result_message_kr'] . $res['remarks'],
                );
                //增加系统消息
                SystemMessageModel::create($message);

                $messageTemplate = MessageTemplateModel::where(['code' => '100005'])->find();
                $replacements = array('{name}' => $to_user['nickname'], '{money}' =>$res['money']);
                $result_message = str_replace(array_keys($replacements), array_values($replacements), $messageTemplate['describe']);
                $shape_create = array(
                    'from_user' => $user_id, 'to_user' => $friend_id,
                    'content' => $result_message . $res['remarks'],
                    'type' => 'gift',
                    'is_read' => 0,
                    'friend_id' => self::getFriendId($user_id, $friend_id),
                );
                event('Service', ['friend_id' => $shape_create['friend_id'],]);
                MessageModel::create($shape_create);

                break;
            case 'recharge':
                self::websocketSendMsg($user_id, $type, '更新充值');
                break;
            case 'follow':
                self::websocketSendMsg($friend_id, $type, '更新关注');
                self::websocketSendMsg($user_id, $type, '更新关注');
                break;
            case 'user_count': # TODO 统计消息 从 websocket 出数据
                $trends_message_number = 2;
                $trends_comment_message_number = 10;
                $user_message_number = 8;
                $message = array(
                    'all_message_number' => $trends_message_number + $trends_comment_message_number + $user_message_number,
                    'trends_message_number' => $trends_message_number,
                    'trends_comment_message_number' => $trends_comment_message_number,
                    'user_message_number' => $user_message_number,
                );
                self::websocketSendMsg($friend_id, $type, $message);
                break;
            default:
                // 聊天消息
                $to_user = UserModel::getUserInfoFind(['id' => $friend_id], 'id,nickname,is_speak_me,is_comment_me,is_private,is_mail');
                if ($to_user['is_speak_me'] == 1 || $to_user['is_speak_me'] == 0) {
                    $user_message_data = ['username' => $to_user['nickname']];
                    $message = array(
                        'user_id' => $user_id,
                        'describe' => env('APP_DEBUG') ? '会员为【 ' . $user_id . ' 】发来的私信' : '',
                        'message' => MessageService::getTemplate('100004', $user_message_data),
                    );

                    self::websocketSendMsg($friend_id, $type, $message);
                    $shape = array(
                        'from_user' => $user_id, 'to_user' => $friend_id, 'content' => '', 'type' => $type,
//                        'is_read' => $to_user['is_speak_me'] == 1 ? 0 : 1,
                        'create_time' => date('Y-m-d H:i:s', time()),
                    );
                    MessageModel::create($shape);
                }

        }
        return true;
    }


    /**发送消息websocket
     * @param $user_id
     * @param $type
     * @param $data
     * @return void
     * @author yuncran@126.com
     */
    private static function websocketSendMsg($user_id, $type, $data)
    {
        $message = json_encode(['type' => $type, 'time' => date('Y-m-d H:i:s', time()), 'data' => $data]);
        try {
            if ($user_id == 0) {
                Gateway::sendToAll($message);
            } else {
                Gateway::sendToUid($user_id, $message);
            }
        } catch (\Exception $e) {
            //忽略错误
        }
    }

    /**
     * 发送聊天记录
     * @param $user_id
     * @param $type
     * @param $data
     * @return null
     * @author yuncran@126.com\
     */
    public static function userSend($user_id, $type, $data)
    {
        return self::websocketSendMsg($user_id, $type, $data);
    }

    /**
     * 获取ID
     * @return void
     * @author yuncran@126.com
     */
    public static function getFriendId($user_id, $to_user_id)
    {
        $arr = [$user_id, $to_user_id];
        sort($arr);
        $relation = implode(',', $arr) . ',';
        $friend = FriendModel::where('relation', $relation)->find();
        return empty($friend) ? 0 : $friend['friend_id'];
    }

}